const sybmolFn = () => {
  return {
    day: '天',
    hour: ':',
    minute: ':'
  }
}
Component({
  options:{
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    startTime: {
      type: null,
      value: 0
    },
    endTime: {
      type: null,
      value: 0
    },
    symbol:{
      type: Object,
      value: sybmolFn()
    }
  },
  data:{
    time: null,
    interval: null,
    _symbol: {}
  },

  observers: {
    time(val){
      if(!val){return}
      if (val.num <= 0) {
        return this.triggerEvent('timeOff');
      }
      clearTimeout(this.data.interval);
      this.data.interval = setTimeout(() => {
        this.setData({ 
          time: this.timer(val.num - 1000)
        })
      },1000)
    }
  },

  lifetimes: {
    attached(){
      Object.assign(this.data._symbol, sybmolFn(), this.data.symbol);
      this.setData({
        _symbol: this.data._symbol
      });
      const timeDiff = this.getDate(this.data.endTime).getTime() - this.getDate(this.data.startTime).getTime();
      this.setData({
        time: this.timer(timeDiff)
      });
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    addZero(num){
      return num > 9 ? num : '0'+num;
    },
    /**
     * 对时间戳进行时间格式化
     */
    timer(num, unit = 1000){
			const day = parseInt(num/(unit * 3600 * 24));
      const hour = parseInt(num/(unit * 3600))%24;
      const minute = parseInt(num/(unit * 60))%60;
      const second = (num / unit)%60;
			return {
        day: this.addZero(day),
        hour: this.addZero(hour),
        minute: this.addZero(minute),
        second: this.addZero(second),
        num
      };
    },
    getDate(stamp){
      if(isFinite(stamp)){
        stamp = stamp.toString().length == 13 ? stamp : stamp * 1000;
      }
      return new Date(stamp);
    }
  }
})
